const addArticle = require('express').Router()
const { CreateArticle } = require('../../mongoDB/mongoDB')
const body = require('body-parser')

addArticle.use(body.urlencoded({extended: false}))

addArticle.post('/article', async (req, res) => {
	const data = JSON.parse(Object.keys(req.body)[0])
	const articleNum = await CreateArticle.find()
	const random = Math.floor(Math.random()*1500 +500)
	const importance = Math.floor(Math.random()*3+1)
	data.content = Object.keys(req.query)[0]
	data.serialNumber = articleNum.length
	data.readings = random
	data.importance = importance
	console.log(data)
	const response = await CreateArticle.create(data)
	res.send(response)
})
addArticle.get('/article', async (req, res) => {
	console.log(req.query)
	const total = await CreateArticle.find()
	const response = await CreateArticle.find().skip((req.query.currentPage -1) * req.query.currentNum).limit(req.query.currentNum - 0)
	const obj = {
		total: total.length,
		response
	}
	res.send(obj)
})
addArticle.put('/article/:id', async (req, res) => {
	const data = JSON.parse(Object.keys(req.body)[0])
	data.content = Object.keys(req.query)[0]
	console.log(data)
	const response = await CreateArticle.updateOne({serialNumber: req.params.id}, data)
	res.send(response)
})
module.exports = addArticle